package com.itheima.intercepter;

import com.alibaba.fastjson.JSON;
import com.itheima.common.TokenHolder;
import com.itheima.constant.TokenConstant;
import com.itheima.domain.Employee;
import com.itheima.exception.NologinException;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class TokenInterceptor implements HandlerInterceptor {
    @Resource
    private RedisTemplate<String, String> redisTemplate;
    @Override
    //原始方法调用执行前的内容
    //返回值类型可以拦截控制的执行,true 放行 ,false终止.
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("Authorization");
        String emp = (String) redisTemplate.opsForValue().get(TokenConstant.EMPLOYEE_TOKEN_PREFIX + token);
        Employee emp2 = JSON.parseObject(emp, Employee.class);
        //将当前操作者的id  存入到Token中

        //如果请求头中没有携带登录认证的token,则抛出token异常
        if (!StringUtils.hasText(emp)) {
            throw new NologinException();
        }
        TokenHolder.setCurrentId(emp2.getId());
        return true;
    }
}
